# RacePanel.py

"""
    Displays the Race panel in the main GUI window
"""

from PySide import QtGui
from PySide import QtCore

import app.Physical as Physical             # physical measurements and accuracy

class RacePanel(QtGui.QWidget):
    def __init__(self, parent=None):
        super(RacePanel, self).__init__()

        # Set up some LED image references
        self.redLed = QtGui.QPixmap("images/Red_Light.png")
        self.greenLed = QtGui.QPixmap("images/Green_Light.png")

        # And some UI elements that we'll need
        self.raceOutput = QtGui.QLabel()
        self.raceOutput.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)        
        self.userSelect = QtGui.QComboBox()        
        self.carSelect = QtGui.QComboBox()        
        self.startButton = QtGui.QPushButton("Start")

        # LED structure
##TODO: this should be dependant on a particular RaceTrack
##      replace with PassChartPanel ?
        self.leds = {}

        # Display the main UI window
        self.buildPanel()
        
##TODO is this the proper one, or is the one in RocketWheels.py the right one
        # Hook the race result signal for results
        parent.raceResult.connect(self.getRaceResult)

    def buildPanel(self):
        # Main vertical layout panel - holds everything in the panel
        mainLayout = QtGui.QVBoxLayout()

        # Horizontal panel holding the three start panels
        startPanelLayout = QtGui.QHBoxLayout()
##TODO: make the 1.2.3. fields larger with an intrusive font 
##      how are the drop down lists initialized?
        # The user-start panel
        userLayout = QtGui.QVBoxLayout()
        userLayout.addWidget(QtGui.QLabel("1. Pick a Driver..."))
        userLayout.addWidget(self.userSelect)

        # The car-start panel
        carLayout = QtGui.QVBoxLayout()
        carLayout.addWidget(QtGui.QLabel("2. Pick a Car..."))
        carLayout.addWidget(self.carSelect)

        # The start-start panel (yeah, I called it that)
        startLayout = QtGui.QVBoxLayout()
        startLayout.addWidget(QtGui.QLabel("3. Start the race!"))
        startLayout.addWidget(self.startButton)

        # Add start panels
        startPanelLayout.addLayout(userLayout)
        startPanelLayout.addLayout(carLayout)
        startPanelLayout.addLayout(startLayout)

        # And add the start layout to the main layout
        mainLayout.addLayout(startPanelLayout)

        # Add the main text output panel
        mainLayout.addWidget(self.raceOutput)
        mainLayout.addStretch(1)

        # Holds the row of LEDs
        ledLayout = QtGui.QHBoxLayout()

        # Build the LED structure
##TODO: this needs to be iterated over a particular RaceTrack
        for station in range(0,6):
            for sensor in range(0,3):
                key = str(station) + "_" + str(sensor)
                self.leds[key] = QtGui.QLabel()
                self.setLed(station,sensor,self.redLed)
                ledLayout.addWidget(self.leds[key])

                if(sensor < 2):
                    ledLayout.addStretch(1)

            if(station < 5):
                ledLayout.addStretch(10)

        # And add it to the main layout
        mainLayout.addLayout(ledLayout)

        # Set the main layout for the panel
        self.setLayout(mainLayout)

    def getRaceResult(self, code="", df=None):
        if code == 'beg':
            (pd,rt) = df # unpack the args

            self.appendOutput("Begin race...\n")
            self.appendOutput("Car: " + str(pd.car_name))
            self.appendOutput("Driver: " + str(pd.driver_name))
            self.appendOutput("Mass: {:3.1f} gm".format(Physical.convert(pd.car_mass,'kg','gm')))
            self.appendOutput("Desc: " + str(pd.description) + "\n")

        elif code == 'run' :
            (pd,rt,stl,s,c) = df # unpack the args

            self.setLed(s,c,self.greenLed)

            v = rt.velocity('mph',stl,s)
            vs = 'None' if v is None else "{:#.3g}".format(v)
            self.appendOutput( "Sensor: {}:{} (mph) {}".format(s,c,vs) )

        elif code == 'end' :
            self.appendOutput("Race Ended.")

        else :
            raise Exception("ERR: my callback got an unexpected code '{}'".format(code))

    def setOutput(self, output=""):
        self.raceOutput.setText(output)

    def appendOutput(self, output=""):
        self.raceOutput.setText(self.raceOutput.text() + "\n" + output)

    def clearOutput(self):
        self.raceOutput.setText("")
        self.resetLEDs()

    def setLed(self,station,sensor,color):
        key = str(station) + "_" + str(sensor)
        self.leds[key].setPixmap(color)

    def resetLEDs(self):
        for station in range(0,6):
            for sensor in range(0,3):
                self.setLed(station,sensor,self.redLed)

    def paintEvent(self,paintEvent):
        painter = QtGui.QPainter(self)
        painter.setPen(QtCore.Qt.blue)
        painter.setFont(QtGui.QFont("Arial",30))
        rect = QtCore.QRect(0,0,10000,10000)
        painter.drawText(rect,QtCore.Qt.AlignCenter,"Qt")
        
